package com.hxzy.shop.commodity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hxzy.shop.commodity.mapper.DrugCarouselMapMapper;
import com.hxzy.shop.commodity.service.DrugCarouselMapService;
import com.hxzy.shop.entity.DrugCarouselMap;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class DrugCarouselMapServiceImpl implements DrugCarouselMapService {

    @Resource
    private DrugCarouselMapMapper drugCarouselMapMapper;

    /**
     * 添加药品轮播图
     *
     * @param drugCarouselMapUrl 轮播图url
     * @param drugUid            商品id
     * @return 是否成功
     */
    @Override
    public boolean addCarouselMap(List<String> drugCarouselMapUrl, Long drugUid) {
        AtomicInteger size = new AtomicInteger(0);
        List<DrugCarouselMap> collect = drugCarouselMapUrl.stream().
                map(e -> new DrugCarouselMap(drugUid, e, size.getAndIncrement())).
                collect(Collectors.toList());
        for (DrugCarouselMap drugCarouselMap : collect) {
            int insert = drugCarouselMapMapper.insert(drugCarouselMap);
            if (insert <= 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 根据id获得药品的轮播图
     *
     * @param id 药品id
     * @return 药品轮播图
     */
    @Override
    public Map<Integer, String> getCarouselMap(Long id) {
        Map<Integer, String> map = new HashMap<>();
        List<DrugCarouselMap> drugCarouselMaps = drugCarouselMapMapper.getCarouselMap(id);
        drugCarouselMaps.forEach(e -> map.put(e.getSort(), e.getUrl()));
        return map;
    }

    @Override
    public boolean updateCarouselMap(List<String> drugCarouselMap, Long drugId) {
        Integer count = drugCarouselMapMapper.selectCount(new LambdaQueryWrapper<DrugCarouselMap>().eq(DrugCarouselMap::getDrugId, drugId));
        if (count > 0) {
            if (drugCarouselMapMapper.delete(new LambdaQueryWrapper<DrugCarouselMap>().eq(DrugCarouselMap::getDrugId, drugId)) > 0) {
                return addCarouselMap(drugCarouselMap, drugId);
            }
        } else if (count == 0) {
            return addCarouselMap(drugCarouselMap, drugId);
        }
        return false;
    }
}
